<?php

require('../coupon/tcpdf.php');
require_once('../coupon/pdf/fpdi.php');
require_once('../coupon/config/lang/eng.php');
require('../wp-load.php');
global $current_user;

function array_to_CSV($data) {

    $outstream = fopen("php://temp", 'r+');
    fputcsv($outstream, $data, ';', '"');
    rewind($outstream);
    $csv = fgets($outstream);
    fclose($outstream);
    return $csv;
    
}
$filterString .= "";
if(@$_GET['contest_id'] == ""){
    $_GET['contest_id'] = "all";
}
if(@$_GET['contest_id'] != "all") {
    $filterString .= " AND cd.contest_id = {$_GET['contest_id']}";
} else {
    $filterString = "";
}


// get data from database
$getVoteSQL = "
            select cdd.data_id, cdd.created_time, cdd.total_like, cdd.contest_name, cl.liked_time, cl.name as facebook_name, cl.birthday
            from (
            select cd.*, cc.name as contest_name from `st_contest_data` cd, st_contest_contest cc where cd.contest_id = cc.contest_id and cc.smt_user_id = {$_GET['smt_user_id']} {$filterString}
            ) cdd,
            (
            SELECT cu.*,liked_time, data_id FROM `st_contest_user_like_data` ul, `st_contest_user` cu WHERE ul.smt_user_id = {$_GET['smt_user_id']} and ul.user_id = cu.user_id
            ) cl
            where cdd.data_id = cl.data_id
            order by liked_time DESC    
";

$name = "All contests";

if(@$_GET['contest_id'] != "all") {
    $contestDetail = $wpdb->get_row("select * from  st_contest_contest where contest_id = {$_GET['contest_id']}");
    $name = $contestDetail->name;    
}

//echo $getVoteSQL;die;

$result = $wpdb->get_results($getVoteSQL);

// export csv
$exportFileName = "votes-" . date_i18n('d-m-Y') . "_" . time();
if ($_GET['format'] == 'csv') {
    header("Content-type: application/octet-stream;charset=UTF-8");
    header("Content-Disposition: csv; filename=\"{$exportFileName}.csv\"");
    $csv = 'User ID;Name;Gender;Email;BirthDate;Home Town;Facebook User ID' . "\n";
    foreach ($result as $row) {        
        $birthday = explode('-', $row->birthday);
        $birthday = $birthday[2] . '.' . $birthday[1] . '.' . $birthday[0];
        $csv .= $row->user_id . ';' . $row->name . ';' . $row->gender . ';' . $row->email . ';' . $birthday . ';' . $row->hometown . ';' . $row->facebook_user_id . "\n";
    }
    $csv = chr(255) . chr(254) . mb_convert_encoding($csv, "UTF-16LE", "UTF-8");
    echo $csv;
} elseif ($_GET['format'] == 'pdf') {

    class PDF extends FPDI {

        /**
         * "Remembers" the template id of the imported page
         */
        var $_tplIdx;
        private $pdf_name;
        private $name;

        function __construct($name, $orientation = 'P', $unit = 'mm', $format = 'A4', $unicode = true, $encoding = 'UTF-8', $diskcache = false) {
            $this->name = $name;
            parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskcache);
        }

        /**
         * include a background template for every page
         */
        function Header() {
            global $current_user;
            if (is_null($this->_tplIdx)) {
                $this->setSourceFile('../coupon/example.pdf');
                $this->_tplIdx = $this->importPage(1);
            }
            $this->useTemplate($this->_tplIdx);
            $this->setFont('freeserif', '', 7);
            $this->writeHTMLCell(27, 0, 187, 9, '<p align="right">' . $this->PageNo() . '/' . $this->getAliasNbPages() . '</p>');
            $this->writeHTMLCell(22, 0, 184, 12, '<p align="right">' . date_i18n('d.m.Y H:i:s') . '</p>');
            $this->setFont('freeserif', 'B', 12);
            $this->writeHTMLCell(0, 0, 0, 10, '<p align="center">USER REPORT<br/> - ' . $this->name . ' - </p>');
            $this->setFont('freeserif', 'B', 8);
            $this->SetXY(5, 31);
            $html = '<table border="0" cellpadding="2" cellspacing="0" width="570">';
            $html .= '<tr style="border-bottom:solid 1px #000000;"><td width="20%"  align="center">Voters FB name</td><td width="20%">Voters age</td><td width="20%" align="center">Date/time for vote</td><td width="40%">Name of contest the vote is for</td></tr>';
            $html .= '</table>';
            $this->writeHTML($html);
        }

        function Footer() {
            
        }

    }

    $pdf = new PDF($name);
    $pdf->SetMargins(PDF_MARGIN_LEFT, 37, PDF_MARGIN_RIGHT);
    $pdf->addPage();

    // End Name 
    $pdf->SetXY(5, 37);
    $pdf->setFont('freeserif', '', 8);
    $html = '<table border="0" cellpadding="2" cellspacing="0" width="570">';
    $stt = 1;
    foreach ($result as $row) {
        $birthday = explode('-', $row->birthday);
        $birthday = $birthday[2] . '.' . $birthday[1] . '.' . $birthday[0];
        $background = '';
        if (($stt % 2) == 0)
            $background = 'style="background-color:#bfe1ff"';        
        $html .= '<tr ' . $background . '><td width="20%"  align="center">' . $row->facebook_name . '</td><td width="20%">' . $row->birthday . '</td><td width="20%" align="center">' . $row->liked_time . '</td><td width="40%">' . $row->contest_name . '</td></tr>';
        $stt++;
    }
    $html .='<tr><td colspan="7"><br style="height:1px;" /><hr style="height:0.7px;font-weight:bold;"></td></tr>';
    $html .= '</table>';
    $pdf->writeHTML($html);   
    $pdf->Output('data/' . $exportFileName . '.pdf', 'F');
    echo "<script>window.location = '" . get_bloginfo('url') . "/contest/data/{$exportFileName}.pdf';
    // window.close();
    </script>";
}
?>